package com.pig4cloud.pig.module.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.MathUtil;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.devices.Devices;
import com.pig4cloud.pig.module.api.entity.dto.MerTableDto;
import com.pig4cloud.pig.module.api.entity.dto.OrderRestaurantSettleDto;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.excel.ProductOrderExcel;
import com.pig4cloud.pig.module.api.entity.excel.ProductOrderMerDetailExcel;
import com.pig4cloud.pig.module.api.entity.excel.ProductOrderMerTotalExcel;
import com.pig4cloud.pig.module.api.entity.mer.Mer;
import com.pig4cloud.pig.module.api.entity.mer.MerSelfVip;
import com.pig4cloud.pig.module.api.entity.mer.MerTable;
import com.pig4cloud.pig.module.api.entity.product.*;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.api.entity.wx.UserIntegralRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.devices.IDevicesService;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.mer.IMerSelfVipService;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.mer.IMerTableService;
import com.pig4cloud.pig.module.service.product.*;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Validated
@Api(value = "订单控制器", tags = {"订单管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/order")
public class ProductOrderController {

    private final IProductOrderService productOrderService;
    private final IProductOrderInfoService productOrderInfoService;
	private final IProductTypeService productTypeService;
	private final IMerService merService;
    private final IPropertyService propertyService;
    private final IEstateService estateService;
	private final IDevicesService devicesService;
	private final IWxUserService wxUserService;
    private final IMerTableService merTableService;
    private final IMerSelfVipService merSelfVipService;
	private final IProductService productService;
	private final IProductAttrValueService productAttrValueService;
    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @PreAuthorize("@pms.hasPermission('module:productorder:list')")
    @GetMapping("/list")
    public TableDataInfo<ProductOrder> list(@Validated ProductOrder productOrder) {
        PigUser sysUser = SecurityUtils.getUser();
        QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        } else if(sysUser.getUserType() == 4){//商家
            qw.eq("mer_id",sysUser.getMerId());
        }else{
            if(productOrder.getPropertyId()!=null){
                qw.eq("property_id",productOrder.getPropertyId());
            }
            if(productOrder.getEstateId()!=null){
                qw.eq("estate_id",productOrder.getEstateId());
            }
            if(productOrder.getMerId()!=null){
                qw.eq("mer_id",productOrder.getMerId());
            }
        }
		if(productOrder.getMerTableId()!=null){
			qw.eq("mer_table_id",productOrder.getMerTableId());
		}
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
        }

        //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 商家优惠券  3 - 线下支付交易
		if(productOrder.getOrderType()!=null){
			if(productOrder.getOrderType() == 1){//1 - 设备上的商品类
				qw.eq("order_type",1);
			}else if (productOrder.getOrderType() == 6){
                qw.eq("order_type",6);
            }else{//0 - 平台商品类  2 - 商家优惠券  3 - 线下支付交易
				qw.ne("order_type",1);
			}
		}

		if(productOrder.getPlatform()!=null){
			qw.eq("platform",productOrder.getPlatform());
		}

		if(productOrder.getPayType()!=null){
			qw.eq("pay_type",productOrder.getPayType());
		}

		if(productOrder.getDeviceId()!=null){
			qw.eq("device_id",productOrder.getDeviceId());
		}

        if(productOrder.getStatus()!=null){
        	if(productOrder.getStatus() == 2){
        		//订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
				Integer[] states = new Integer[]{ 2, 3, 4 };
				qw.in("status",states);
			} else if(productOrder.getStatus() == 0){
				Integer[] states = new Integer[]{ 0,1 };
				qw.in("status",states);
			}else{
				qw.eq("status",productOrder.getStatus());
			}
		}

        if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
            qw.like("order_no",productOrder.getOrderNo());
        }
        qw.orderByDesc("create_time");
		TableDataInfo<ProductOrder> td = PageUtils.buildDataInfo(productOrderService.page(PageUtils.buildPage(),qw));
        List<ProductOrder> list = td.getData();
        list.forEach(order->{
			Mer mer = merService.getById(order.getMerId());
			if(mer != null){
				order.setShopName(mer.getShopName());
			}

            Estate estate = estateService.findById(order.getEstateId());
            if(estate!=null){
                order.setEstateName(estate.getEstateName());
            }
            if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

            WxUser wxUser = wxUserService.findById(order.getUserId());
			if(wxUser!=null){
				if(StrUtil.isNotEmpty(wxUser.getNickName())){
					order.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
				}
			}

            Property property = propertyService.findById(order.getPropertyId());
            if(property!=null){
                order.setPropertyName(property.getPropertyName());
            }
            if (order.getMerTableId()!=0){
                MerTable merTable = merTableService.findById(order.getMerTableId());
                if (ObjectUtil.isNotEmpty(merTable)){
                    order.setMerTableName(merTable.getTableName());
                }
            }
            if(order.getOrderType() == 1){
            	Devices devices = devicesService.findById(order.getDeviceId());
            	if(devices!=null){
            		order.setDeviceName(devices.getDeviceName()  + "("+devices.getDeviceSn()+")");
				}
			}

			if(productOrder.getIsShowInfo() != null && productOrder.getIsShowInfo() == 1){
				order.setIsCheck(true);
				QueryWrapper<ProductOrderInfo> qwInfo = new QueryWrapper<>();
				qwInfo.eq("order_id",order.getId());
				List<ProductOrderInfo> listInfo = productOrderInfoService.list(qwInfo);
				if(CollUtil.isNotEmpty(listInfo)){
					for (ProductOrderInfo orderInfo : listInfo){
						if(StrUtil.isEmpty(orderInfo.getSkuName())){
							ProductAttrValue productAttrValue = productAttrValueService.findById(orderInfo.getSkuId());
							if(productAttrValue!=null){
								orderInfo.setSkuName(productAttrValue.getSku());
							}
						}
						Product product = productService.findById(orderInfo.getProductId());
						if(product!=null){
							orderInfo.setProductName(product.getStoreName());
						}
					}
				}
				order.setOrderInfos(listInfo);

				MerSelfVip selfVip = merSelfVipService.findById(order.getSelfVipId());
				order.setSelfVip(selfVip);

			}
		});

		Map<String,Object> map = new HashMap<>();


		QueryWrapper<MerTable> qwTable = new QueryWrapper<>();
		qwTable.eq("mer_id", productOrder.getMerId());
		qwTable.orderByAsc("table_no");

		List<MerTable> merTables = merTableService.list(qwTable);
		map.put("merTables",merTables);

		MerTable table = merTableService.findById(productOrder.getMerTableId());
		if(table!= null){
			map.put("table",table);
		}

		map.put("discountRate", 0);
		if(productOrder.getMerId()!=null){
			Mer mer = merService.getById(productOrder.getMerId());
			if(mer!= null){
				map.put("discountRate", mer.getDiscountRate());
			}
		}
		td.setOtherData(map);

        return td;
    }

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/statistics/list")
    public TableDataInfo<ProductOrderExcel> statisticsList(@Validated ProductOrder productOrder) {
        Map<String,Object> map = new HashMap<>();
        PigUser sysUser = SecurityUtils.getUser();
        if(sysUser.getUserType() == 2){//物业公司
            map.put("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            map.put("estate_id",sysUser.getEstateId());
        }
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
            map.put("end_time",productOrder.getBeginDate() + " 23:59:59");
        }
        TableDataInfo<ProductOrderExcel> td = PageUtils.buildDataInfo(productOrderService.selectPageExcelListByTime(PageUtils.buildPage(),map));
        return td;
    }

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/mer/list")
    public TableDataInfo<ProductOrder> merList(@Validated ProductOrder productOrder) {
        Map<String,Object> map = new HashMap<>();
        PigUser sysUser = SecurityUtils.getUser();
        if(sysUser.getUserType() == 2){//物业公司
            map.put("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            map.put("estate_id",sysUser.getEstateId());
        } else if(sysUser.getUserType() == 4){//商家
            map.put("mer_id",sysUser.getMerId());
        }
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
            map.put("end_time",productOrder.getBeginDate() + " 23:59:59");
        }


		map.put("order_type", productOrder.getOrderType());

        if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
            map.put("order_no", productOrder.getOrderNo());
        }
		if(productOrder.getStatus()!=null){
			map.put("status",productOrder.getStatus());
		}

		if(productOrder.getIsVerify()!=null){
            map.put("is_verify",productOrder.getIsVerify());
        }

        TableDataInfo<ProductOrder> td = PageUtils.buildDataInfo(productOrderInfoService.selectOrderListByMer(PageUtils.buildPage(),map));
        List<ProductOrder> list = td.getData();
        list.forEach(order->{
            Mer mer = merService.getById(order.getMerId());
            if(mer != null){
                order.setShopName(mer.getShopName());
            }

            Estate estate = estateService.findById(order.getEstateId());
            if(estate!=null){
                order.setEstateName(estate.getEstateName());
            }

            Property property = propertyService.findById(order.getPropertyId());
            if(property!=null){
                order.setPropertyName(property.getPropertyName());
            }
        });
        return td;
    }
    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/listByFenrun")
    public TableDataInfo<ProductOrder> listByFenrun(@Validated ProductOrder productOrder) {
        PigUser sysUser = SecurityUtils.getUser();
        QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
        if(sysUser!=null){
            if(sysUser.getUserType() == 2){//物业公司
                qw.eq("property_id",sysUser.getPropertyId());
            } else if(sysUser.getUserType() == 3){//小区
                qw.eq("estate_id",sysUser.getEstateId());
            } else if(sysUser.getUserType() == 4) {//商家
            	if(productOrder.getMerId()!=null){
					qw.eq("mer_id",productOrder.getMerId());
				}else{

					List<Integer> merIds = new ArrayList<>();
					Map<String,Object> map = new HashMap<>();
					map.put("sys_user_id",sysUser.getId());
					List<Mer> list = merService.selectMerListByUserId(map);
					if(CollUtil.isNotEmpty(list)){
						for (Mer mer : list){
							merIds.add(mer.getId());
						}
					}
					if(merIds.size() > 0){
						qw.in("mer_id",merIds);
					}else{
						qw.in("mer_id",sysUser.getMerId());
					}
				}
            }
        }
        qw.in("status",new Integer[]{ 2, 3, 4 });
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
        }

        qw.orderByDesc("create_time");
        TableDataInfo<ProductOrder> td = PageUtils.buildDataInfo(productOrderService.page(PageUtils.buildPage(),qw));
        List<ProductOrder> list = td.getData();
        list.forEach(order -> {
            Mer mer = merService.getById(order.getMerId());
            if(mer!=null){
                order.setShopName(mer.getShopName());
            }
            if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

        });
        Map<String,Object> map = new HashMap<>();
        map.put("userType",sysUser.getUserType());


        //今日交易额
        Map<String,Object> mapOrder = new HashMap<>();
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())) {
            mapOrder.put("begin_time", productOrder.getBeginDate() + " 00:00:00");
            mapOrder.put("end_time", productOrder.getEndDate() + " 23:59:59");
        }

        if(sysUser!=null){
            if(sysUser.getUserType() == 2){//物业公司

            	//总交易金额
                mapOrder.put("property_id",sysUser.getPropertyId());
                double orderMoneyAll = productOrderService.selectTotalMoneyByTime(mapOrder);
                map.put("orderMoneyAll",orderMoneyAll);

                // 总分润
                double fenRunProperty = productOrderService.selectFenRunProperty(mapOrder);
                map.put("fenRun",fenRunProperty);
            } else if(sysUser.getUserType() == 3){//小区
                mapOrder.put("estate_id",sysUser.getEstateId());

                //总交易金额
                double orderMoneyAll = productOrderService.selectTotalMoneyByTime(mapOrder);
                map.put("orderMoneyAll",orderMoneyAll);

                //总分润
                double fenRunProperty = productOrderService.selectFenRunEstate(mapOrder);
                map.put("fenRun",fenRunProperty);
            }else if(sysUser.getUserType() == 4){//商家
            	if(productOrder.getMerId() !=null){
					mapOrder.put("mer_id",productOrder.getMerId());
				}else{
					mapOrder.put("mer_id",0);
				}
				mapOrder.put("sys_user_id",sysUser.getId());
				//总交易金额
				Map<String,Object> orderMoneyAll = productOrderService.selectFenRunMer(mapOrder);
				map.putAll(orderMoneyAll);
            }else {//平台
            	//总交易金额
                double orderMoneyAll = productOrderService.selectTotalMoneyByTime(mapOrder);
                map.put("orderMoneyAll",orderMoneyAll);

                double fenRunPlatform = productOrderService.selectFenRunPlatform(mapOrder);
                map.put("fenRun",fenRunPlatform);
            }
        }
        td.setOtherData(map);
        return td;
    }

    /**
     * 导出订单列表
     */
    @ApiOperation("导出订单列表")
    @PreAuthorize("@pms.hasPermission('module:productorder:export')")
    @SysLog("订单")
    @GetMapping("/export")
    public List export(@Validated ProductOrder productOrder) {
        PigUser sysUser = SecurityUtils.getUser();
        QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        } else if(sysUser.getUserType() == 4){//商家
            qw.eq("mer_id",sysUser.getMerId());
        }else{
            if(productOrder.getPropertyId()!=null){
                qw.eq("property_id",productOrder.getPropertyId());
            }
            if(productOrder.getEstateId()!=null){
                qw.eq("estate_id",productOrder.getEstateId());
            }
            if(productOrder.getMerId()!=null){
                qw.eq("mer_id",productOrder.getMerId());
            }
        }
        if(productOrder.getMerTableId()!=null){
            qw.eq("mer_table_id",productOrder.getMerTableId());
        }
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
        }

        //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 商家优惠券  3 - 线下支付交易
        if(productOrder.getOrderType()!=null){
            if(productOrder.getOrderType() == 1){//1 - 设备上的商品类
                qw.eq("order_type",1);
            }else if (productOrder.getOrderType() == 6){
                qw.eq("order_type",6);
            }else{//0 - 平台商品类  2 - 商家优惠券  3 - 线下支付交易
                qw.ne("order_type",1);
            }
        }

        if(productOrder.getPlatform()!=null){
            qw.eq("platform",productOrder.getPlatform());
        }

        if(productOrder.getPayType()!=null){
            qw.eq("pay_type",productOrder.getPayType());
        }

        if(productOrder.getDeviceId()!=null){
            qw.eq("device_id",productOrder.getDeviceId());
        }

        if(productOrder.getStatus()!=null){
            if(productOrder.getStatus() == 2){
                //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                Integer[] states = new Integer[]{ 2, 3, 4 };
                qw.in("status",states);
            } else if(productOrder.getStatus() == 0){
                Integer[] states = new Integer[]{ 0,1 };
                qw.in("status",states);
            }else{
                qw.eq("status",productOrder.getStatus());
            }
        }

        if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
            qw.like("order_no",productOrder.getOrderNo());
        }
        qw.orderByDesc("create_time");
        List<ProductOrder> list = productOrderService.list(qw);
//        List<ProductOrder> list = td.getData();
        for (ProductOrder list1:list){
            if (list1.getEstateId()!=null){
                Estate estate = estateService.getById(list1.getEstateId());
                if (ObjectUtil.isNotEmpty(estate)){
                    list1.setEstateName(estate.getEstateName());
                }
            }
            if (list1.getPropertyId()!=null){
                Property property = propertyService.getById(list1.getPropertyId());
                if (ObjectUtil.isNotEmpty(property)) {
                    list1.setPropertyName(property.getPropertyName());
                }
            }
            if (list1.getUserId()!=null){
                WxUser user = wxUserService.getById(list1.getUserId());
                if (ObjectUtil.isNotEmpty(user)) {
                    list1.setNickName(user.getNickName());
                }
            }
            if (list1.getCreateTime()!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list1.setPayTimes(sdf.format(list1.getCreateTime()));
            }
        }
        // ExcelUtil<ProductOrder> util = new // ExcelUtil<ProductOrder>(ProductOrder.class);
        return  list;// util.exportExcel(list, "订单");
    }


    /**
     * 导出用户的积分记录列表
     */
    @ApiOperation("物业总数据导出")
    @PreAuthorize("@pms.hasPermission('module:productorder:export')")
    @SysLog("物业总数据导出")
    @GetMapping("/exportTotal")
    public List exportTotal(@Validated  ProductOrder productOrder) {
        Map<String,Object> map = new HashMap<>();

		if(productOrder.getOrderType()!=null){
			map.put("order_type",productOrder.getOrderType());
		}
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
            map.put("end_time",productOrder.getEndDate() + " 23:59:59");
        }
        List<ProductOrderExcel> list = productOrderService.selectExcelListByTime(map);
        // ExcelUtil<ProductOrderExcel> util = new // ExcelUtil<>(ProductOrderExcel.class);
        return  list;// util.exportExcel(list, "所有消费统计记录");
    }


	/**
	 * 商家总数据导出
	 */
	@ApiOperation("商家总数据导出")
	@PreAuthorize("@pms.hasPermission('module:productorder:export')")
	@SysLog("商家总数据导出")
	@GetMapping("/exportMerTotal")
	public List exportMerTotal(@Validated  ProductOrder productOrder) {
		Map<String,Object> map = new HashMap<>();
        if(productOrder.getMerId()!=null){
            map.put("mer_id",productOrder.getMerId());
        }
		map.put("order_type",0);
		if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
			map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
			map.put("end_time",productOrder.getEndDate() + " 23:59:59");
		}
		List<ProductOrderMerTotalExcel> list = productOrderService.selectExcelMerTotalListByTime(map);
		// ExcelUtil<ProductOrderMerTotalExcel> util = new // ExcelUtil<>(ProductOrderMerTotalExcel.class);
		return  list;// util.exportExcel(list, "商家核销订单统计");
	}


	/**
	 * 商家明细导出
	 */
	@ApiOperation("商家明细导出")
	@PreAuthorize("@pms.hasPermission('module:productorder:export')")
	@SysLog("商家明细导出")
	@GetMapping("/exportMerDetail")
	public List exportMerDetail(@Validated  ProductOrder productOrder) {
		Map<String,Object> map = new HashMap<>();
        if(productOrder.getMerId()!=null){
            map.put("mer_id",productOrder.getMerId());
        }
        map.put("order_type",0);
		if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
			map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
			map.put("end_time",productOrder.getEndDate() + " 23:59:59");
		}
		List<ProductOrderMerDetailExcel> list = productOrderService.selectExcelMerDetailListByTime(map);
		// ExcelUtil<ProductOrderMerDetailExcel> util = new // ExcelUtil<>(ProductOrderMerDetailExcel.class);
		return  list;// util.exportExcel(list, "所有消费统计记录");
	}

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:productorder:query')")
    @GetMapping("/{id}")
    public R<ProductOrder> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
    	ProductOrder order = productOrderService.getById(id);
    	if(order!=null){
			Mer mer = merService.getById(order.getMerId());
			if(mer != null){
				order.setShopName(mer.getShopName());
			}

			Estate estate = estateService.findById(order.getEstateId());
			if(estate!=null){
				order.setEstateName(estate.getEstateName());
			}
			if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

			Property property = propertyService.findById(order.getPropertyId());
			if(property!=null){
				order.setPropertyName(property.getPropertyName());
			}
		}
        return R.ok(order);
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:productorder:query')")
    @GetMapping("/mer/{id}")
    public ProductOrder getOrderInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrder order = productOrderService.getById(id);
        if(order!=null){
            Mer mer = merService.getById(order.getMerId());
            if(mer != null){
                order.setDiscountRate(mer.getDiscountRate());
                double total = order.getTotalPrice().doubleValue();
                double zhekou = order.getDiscountRate().doubleValue();
                System.out.println(total+"======应付");
                System.out.println(zhekou+"======折扣");
                double pay = MathUtil.getDoubleUp(total * zhekou/10);
                double dk = MathUtil.getDoubleUp(total-pay);
                order.setPay(pay);
                String pay1 = String.valueOf(pay);
                String dikou = String.valueOf(dk);
                BigDecimal bigDecimal = new BigDecimal(pay1);
                BigDecimal bigDecimal2 = new BigDecimal(dikou);
                order.setPayPrice(bigDecimal);
                System.out.println(order.getPayPrice()+"======支付");
                order.setDiscountDikouPrice(bigDecimal2);
                boolean ret = productOrderService.updateById(order);
            }
        }
        return order;
    }
	/**
	 * 获取订单详细信息
	 */
	@ApiOperation("获取订单详细信息")
	@PreAuthorize("@pms.hasPermission('module:productorder:query')")
	@GetMapping("/print/{id}")
	public R<Void> printOrder(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
		ProductOrder order = productOrderService.getById(id);
		if(order!=null){
			productOrderService.print(order);
			return R.ok();
		}
		return R.failed();
	}


    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:productorder:query')")
    @GetMapping("/print0/{id}")
    public R<Void> printOrder0(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrder order = productOrderService.getById(id);
        if(order!=null){
            productOrderService.print0(order);
            return R.ok();
        }
        return R.failed();
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:productorder:query')")
    @GetMapping("/print1/{id}")
    public R<Void> printOrder1(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrder order = productOrderService.getById(id);
        if(order!=null){
            productOrderService.print1(order);
            return R.ok();
        }
        return R.failed();
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:productorder:query')")
    @GetMapping("/print2/{id}")
    public R<Void> printOrder2(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrder order = productOrderService.getById(id);
        if(order!=null){
            productOrderService.print2(order);
            return R.ok();
        }
        return R.failed();
    }
    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:productorder:query')")
    @GetMapping("/printCounter/{id}")
    public R<Void> printOrderCounter(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrder order = productOrderService.getById(id);
        if(order!=null){
            productOrderService.printCounter(order);
            return R.ok();
        }
        return R.failed();
    }
	/**
     * 新增订单
     */
    @ApiOperation("新增订单")
    @PreAuthorize("@pms.hasPermission('module:productorder:add')")
    @SysLog("订单")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody ProductOrder productOrder) {
        return R.okByRow(productOrderService.save(productOrder) ? 1 : 0);
    }

    /**
     * 修改订单
     */
    @ApiOperation("修改订单")
    @PreAuthorize("@pms.hasPermission('module:productorder:edit')")
    @SysLog("订单")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody ProductOrder productOrder) {
        boolean ret = productOrderService.updateById(productOrder);
        return R.okByRow(ret);
    }

    /**
     * 修改订单
     */
    @ApiOperation("修改订单")
    @PreAuthorize("@pms.hasPermission('module:productorder:edit')")
    @SysLog("订单")

    @PutMapping("/vip")
    public R<Void> editVip(@Valid @RequestBody ProductOrder productOrder) {
        if (productOrder.getSelfVipId()!=null){
            MerSelfVip merSelfVip = merSelfVipService.getById(productOrder.getSelfVipId());
			if(merSelfVip!= null){
				double yue = MathUtil.getDoubleUp(merSelfVip.getAccountMoney().doubleValue());
				double pay = MathUtil.getDoubleUp(productOrder.getPayPrice().doubleValue());
				double account = yue - pay;
				String acc = String.valueOf(account);
				BigDecimal bigDecimal = new BigDecimal(acc);
				merSelfVip.setAccountMoney(bigDecimal);
				boolean jiesuan = merSelfVipService.updateById(merSelfVip);
				if (!jiesuan){
					return R.okByRow(false);
				}
			}
        }else {
            return R.okByRow(false);
        }
        boolean ret = productOrderService.updateById(productOrder);
        return R.okByRow(ret);
    }


	/**
	 *  账单结算
	 */
	@ApiOperation("账单结算")
	@PreAuthorize("@pms.hasPermission('module:productorder:edit')")
	@SysLog("订单")

	@PutMapping("/restaurant/settle")
	public R<Void> restaurantSettle(@Valid @RequestBody OrderRestaurantSettleDto settleDto) {
        PigUser sysUser = SecurityUtils.getUser();
		int ret = productOrderService.settleMerOrder(sysUser,settleDto);
		return R.okByRow(ret);
	}

	/**
	 * 查询服务商家列表
	 */
	@ApiOperation("查询服务商家列表")
	@GetMapping("/restaurant/product/echart")
	public R restaurantProductEChart(@Validated ProductOrder productOrder) {

		List<Map<String, Object>> allData = new ArrayList<>();
		QueryWrapper<ProductType> qwType = new QueryWrapper<>();
		qwType.eq("mer_id", productOrder.getMerId());
        qwType.eq("mer_id", productOrder.getMerId());
		qwType.orderByAsc("sort");
		List<ProductType> types = productTypeService.list(qwType);
		if(CollUtil.isNotEmpty(types)){
			for (ProductType type : types){

				Map<String, Object> map = new HashMap<>();
				map.put("typeName",type.getTypeName());

				List<String> productNames = new ArrayList<>();
				List<String> saleCounts = new ArrayList<>();
				List<String> colors = new ArrayList<>();
				QueryWrapper<Product> qw = new QueryWrapper<>();
				qw.eq("mer_id", productOrder.getMerId());
				qw.eq("cate_id", type.getId());
                qw.eq("is_tableware", 0);
				List<Product> products = productService.list(qw);
				if(CollUtil.isNotEmpty(products)){
					for (Product product : products){
						productNames.add(product.getStoreName());

						Integer count = productOrderInfoService
							.getProductCountByInfo(productOrder.getMerId(), product.getId(),productOrder.getBeginDate(),productOrder.getEndDate());
						saleCounts.add(String.valueOf(count));
						colors.add("'#FCB727'");
					}
				}

				map.put("colors",colors);
				map.put("productNames",productNames);
				map.put("saleCounts",saleCounts);

				if(productNames.size() > 0){
                    allData.add(map);
                }
			}
		}

		return R.ok(allData);
	}


	/**
	 * 修改桌号
	 */
	@ApiOperation("修改订单")
	@PreAuthorize("@pms.hasPermission('module:productorder:edit')")
	@SysLog("订单")

	@PutMapping("/changeTable")
	public R<Void> changeTable(@Valid @RequestBody MerTableDto merTableDto) {
		int ret = productOrderService.changeOrderTable(merTableDto);
		return R.okByRow(ret);
	}



	@SysLog("重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('module:merTable:edit')")
    public R<Void> resetQrCode(@RequestBody ProductOrder productOrder) {
        if(productOrder.getId()!=null){
            try{
                productOrder = productOrderService.getById(productOrder.getId());
                if(productOrder != null){
                    String qrCode = "";
                    String fileName = "";
                    String content = "";
                    fileName = "product_order_" + productOrder.getOrderNo() + ".jpg";
                    content = "https://www.sdyuedou.com/wxmini/order/qr?order_id=" + productOrder.getId();

                    int upload_type = 0;//FileUploadUtils.TYPE_PRODUCT_ORDER;
                    System.out.println("content:  "+ content);
                    String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, productOrder.getOrderNo(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
                    qrCode = img_key;
                    productOrder.setQrCodeUrl(qrCode);
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (productOrderService.updateById(productOrder)) {
                return R.ok();
            }
        }
        return R.failed();
    }


    /**
	 * 修改订单
	 */
	@ApiOperation("修改订单")
	@PreAuthorize("@pms.hasPermission('module:productorder:edit')")
	@SysLog("订单")

	@PutMapping("/refund")
	public R<Void> refund(@Valid @RequestBody ProductOrder productOrder) {
		int ret = productOrderService.refundOp(productOrder);
		return R.okByRow(ret);
	}

    /**
     * 删除订单
     */
    @ApiOperation("删除订单")
    @PreAuthorize("@pms.hasPermission('module:productorder:remove')")
    @SysLog("订单")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return R.okByRow(productOrderService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    /**
     * 核销订单
     */
    @ApiOperation("核销订单")
    @PreAuthorize("@pms.hasPermission('module:productorder:verify')")
    @SysLog("订单" )
    @PostMapping("/verify/{ids}")
    public R<Void> verify(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        for (Long id : ids) {
            ProductOrderInfo orderInfo = productOrderInfoService.getById(id);
            if(orderInfo!=null){
                if(orderInfo.getIsVerify() == 0){
                    orderInfo.setIsVerify(1);
                    productOrderInfoService.updateById(orderInfo);
                }
            }
        }
        return R.okByRow(1);
    }
}
